package com.yilee.idouban.xml.handler;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.yilee.idouban.bean.Person;

/**
 * person xml的handler 形式如 http://api.douban.com/people/yilee
 * 
 * @author yilee
 * 
 */
public class SAXPersonContentHandler extends DefaultHandler {

	private Person person;
	private String preTag;

	public Person getPerson() {
		return person;
	}

	@Override
	public void startDocument() throws SAXException {
		person = new Person();
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		if (person != null) {
			String data = new String(ch, start, length);
			if ("id".equals(preTag)) {
				person.setPersonId(data);
			} else if ("title".equals(preTag)) {
				person.setTitle(data);
			} else if ("content".equals(preTag)) {
				person.setContent(data);
			} else if ("location".equals(preTag)) {
				person.setLocation(data);
			} else if ("uid".equals(preTag)) {
				person.setUid(data);
			}
		}
		super.characters(ch, start, length);
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// link有多个,特殊处理
		if ("link".equalsIgnoreCase(localName)) {
			String rel = attributes.getValue("rel");
			if ("alternate".equalsIgnoreCase(rel)) {
				person.setLink(attributes.getValue("href"));
			} else if ("icon".equalsIgnoreCase(rel)) {
				person.setIcon(attributes.getValue("href"));
			}
		} else if ("location".equalsIgnoreCase(localName)) { //获取location的ID
			person.setLocationId(attributes.getValue("id"));
			preTag = localName;
		} else {
			preTag = localName;
		}

	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		preTag = null;
		super.endElement(uri, localName, qName);
	}

	@Override
	public void endDocument() throws SAXException {
		super.endDocument();
	}

}
